package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders, HttpServletRequest request){
        ordersService.submit(orders);
        return R.success(null);
    }

    /*
    查看订单，实际就是查看订单表中的数据，进行页面展示,并对订单详细表进行封装和表示
     */
    @GetMapping("/userPage")
    public R userPage(@RequestParam int page,@RequestParam int pageSize){
        Page<Orders> ordersPageInfo = new Page<>();
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
        lqw.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(ordersPageInfo, lqw);

        Page<OrderDto> OrderDtoPageInfo = new Page<>(page,pageSize);//为后面做准备,比如复制它的页数呀
        BeanUtils.copyProperties(ordersPageInfo, OrderDtoPageInfo,"records");
        List<Orders> records = ordersPageInfo.getRecords();
        List<OrderDto> collect = records.stream().map((orders) -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(orders, orderDto);
            Long ordersId = orders.getId();//根据订单id查询订单详细
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, ordersId);
            //一个订单多个订单明细
            List<OrderDetail> orderDetail = orderDetailService.list(orderDetailLambdaQueryWrapper);
            orderDto.setOrderDetails(orderDetail);
            return orderDto;
        }).collect(Collectors.toList());//现在把orders转换为ordersdetail。订单表和订单明细表为一对多。
        OrderDtoPageInfo.setRecords(collect);
        return R.success(OrderDtoPageInfo);
    }

    /*
    再来一单逻辑:
        实际上是根据当前订单id找到这个订单记录，然后查找菜品，然后在购物车中添加这2个菜品。
     */
    @PostMapping("/again")
    public R againOrder(@RequestBody Orders orders){
        Long id = orders.getId();//获取订单id
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> list = orderDetailService.list(lqw);//获取到菜品或者套餐
        //把套餐或者菜品添加到购物车
        List<ShoppingCart> collect = list.stream().map((item) -> {//list实际上就是包含订单id套餐id口味数量价格的，名字的值
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(BaseContext.getCurrentId());//设置userid
            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setDishId(item.getDishId());
            shoppingCart.setSetmealId(item.getSetmealId());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(collect);
        return R.success(null);
    }

    /*
    网页端订单管理，此时session里面保存的是现在的emp中的id，拿不到user表中的id。
            beginTime: 2024-05-26 00:00:00
            endTime: 2024-06-01 23:59:59   ---->为前端传递的时间格式。
     */
    @GetMapping("/page")
    public R pageWeb(int page, int pageSize, Long number,
                     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime,
                     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime){
        log.info("获取参数开始时间为：{}，结束时间为：{}", beginTime,endTime);
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime);//根据结账时间降序
        if (number!=null){
            lqw.eq(Orders::getNumber, number);//根据订单号查询
        }
        if (beginTime!=null && endTime!=null){
            lqw.between(Orders::getOrderTime, beginTime,endTime );
        }
        ordersService.page(ordersPage,lqw);

        return R.success(ordersPage);
    }

    @PutMapping
    public R updateStatus(@RequestBody Orders orders){
        LambdaUpdateWrapper<Orders> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(Orders::getId, orders.getId()).set(Orders::getStatus,orders.getStatus());
        ordersService.update(null,lqw);
        return R.success(null);
    }

}
